export function parseParagraphToMarkdown(blocks) {
	return `${blocks.text}\n`
}

function getTagSrcValue(tag) {
	const regex = /src="([^"]+)"/
	const match = tag.match(regex)

	if (match) {
		const src = match[1]
		return src
	}
	return ""
}

function getTableArr(markdownTable) {
	// 去除开头的 "|" 和每行开头的空格
	const rows = markdownTable.split("\n").map((row) => row.replace(/^\s*\|/, "").trim())

	// 提取标题行和数据行
	const header = rows[0].split("|")
	const data = rows.slice(1).map((row) => row.split("|"))

	// 去除标题和数据中的空字符串
	const headerClean = header.filter((item) => item !== "")
	const dataClean = data.map((row) => row.filter((item) => item !== ""))

	return [headerClean, ...dataClean]
}

function isMdTable(str) {
	const lines = str.split("\n")

	// 检查是否至少有两行且每行以 "|" 开头
	if (lines.length < 2 || !lines[0].startsWith("|") || !lines[1].startsWith("|")) {
		return false
	}

	// 检查每一行是否都包含 "|"
	for (const line of lines) {
		if (!line.includes("|")) {
			return false
		}
	}

	return true
}

export function parseMarkdownToParagraph(blocks) {
	let paragraphData = {}
	let str = ""

	if (blocks.type === "paragraph") {
		blocks.children.forEach((item) => {
			if (["text", "html", "inlineCode"].includes(item.type)) {
				if (/^<audio/.test(item.value)) {
					paragraphData = {
						data: {
							url: getTagSrcValue(item.value),
						},
						type: "audio",
					}
				} else if (/\<\/audio\>$/.test(item.value)) {
					// ...
				} else if (/^<video/.test(item.value)) {
					paragraphData = {
						data: {
							url: getTagSrcValue(item.value),
						},
						type: "video",
					}
				} else if (/\<\/video\>$/.test(item.value)) {
					// ...
				} else {
					str += item.value
					paragraphData = {
						data: {
							text: str,
						},
						type: "paragraph",
					}
				}
			}
			if (item.type === "image") {
				console.log("item", item)
				paragraphData = {
					data: {
						caption: item.title,
						stretched: false,
						file: {
							url: item.url,
						},
						withBackground: false,
						withBorder: false,
					},
					type: "image",
				}
			}
			if (item.type === "link") {
				paragraphData = {
					data: {
						link: item.url,
						meta: {
							title: item.title,
							description: item.description || item.title,
						},
					},
					type: "link",
				}
			}
		})
	}

	if (paragraphData.type === "paragraph") {
		if (isMdTable(paragraphData.data.text)) {
			let content = getTableArr(paragraphData.data.text)
			paragraphData = {
				data: {
					content: content.filter((v, i) => i !== 1),
					withHeadings: true,
				},
				type: "table",
			}
		}
	}
	return paragraphData
}

